#!/usr/bin/env bash
INSTALL_DIR=/opt/adc/ztp-api
SERVICE_NAMES=(avl-ztp-api
avl-ztp-sua
avl-ztp-daphne)

SERVICE_TEMPLATE_NAMES=(template.uwsgi.service
template.sua.service
template.daphne.service)

BASE_DIR=$(cd `dirname $0`; pwd)
# 检查安装目录
if [[ $BASE_DIR != $INSTALL_DIR ]]; then
	echo ">>ERROR: work path, please ensure workpath is $INSTALL_DIR "
    exit
fi
# 添加权限避免出现意外
chown -R root:root $INSTALL_DIR

# 清理服务
services_count=${#SERVICE_NAMES[@]}
for i in `seq $services_count`;
do
    systemctl disable ${SERVICE_NAMES[i-1]}
    systemctl stop ${SERVICE_NAMES[i-1]}
    systemctl status ${SERVICE_NAMES[i-1]}
done

# 安装python运行依赖模块
cd $BASE_DIR
python3 -m venv env
source env/bin/activate
pip3 install --upgrade pip
pip3 install -r requirements.txt
if [[ $? != 0 ]]; then
	echo ">>ERROR: pip3 install error, quit! you can try again..."
    exit 255
fi
# 初始化数据库表
python3 manage.py migrate
if [[ $? != 0 ]]; then
	echo ">>ERROR: migrate error, quit! you must fix something..."
    exit 255
fi
deactivate

# 启动服务
for i in `seq $services_count`;
do
    sed "s@\${BASE_DIR}@${BASE_DIR}@g" deployment/${SERVICE_TEMPLATE_NAMES[i-1]} > /usr/lib/systemd/system/${SERVICE_NAMES[i-1]}.service
done
sed "s@%(BASE_DIR)@${BASE_DIR}@g"  deployment/template.uwsgi.ini > deployment/uwsgi_dev.ini
sed -i "s@0.0.0.0@127.0.0.1@g"  deployment/uwsgi_dev.ini
systemctl daemon-reload
for i in `seq $services_count`;
do
    systemctl enable ${SERVICE_NAMES[i-1]}
    systemctl start ${SERVICE_NAMES[i-1]}
done

# 检查服务
sleep 3
for i in `seq $services_count`;
do
    systemctl status ${SERVICE_NAMES[i-1]}
    if [[ $(systemctl status ${SERVICE_NAMES[i-1]} |grep "Active: active (running)") != "" ]]; then
        echo ">>OK: install ${SERVICE_NAMES[i-1]} ok"
    else
        echo ">>ERROR: install ${SERVICE_NAMES[i-1]} error, quit"
        exit 255
    fi
done
